package gob.osinerg.emergencia.dao;

import gob.osinerg.emergencia.bean.EmergenciaOperativaPreliminar;
import gob.osinerg.emergencia.bean.FormularioEmergenciaUnmay;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class EmergenciaOperativaPreliminarDAOImpl extends GenericDAOImpl implements EmergenciaOperativaPreliminarDAO{

	public void save(EmergenciaOperativaPreliminar bean, FormularioEmergenciaUnmay beanform) throws Exception {
		Session session = getSession();
		Transaction transaction = null;
		DecimalFormat formateador = new DecimalFormat("0000");
		try {
			transaction = session.beginTransaction();
			if(beanform.getId() == null){
				beanform.setId(getNextPK("FRM_EMR_UM_SEQ"));
			}
			if(bean.getId() == null){
				bean.setId(getNextPK("EM_OP_PRE_SEQ"));
			}
			if(beanform.getNmroEmrgncia() == null){
				//bean.setIdFormato("F3"+formateador.format(bean.getId()));
				beanform.setNmroEmrgncia("F3"+formateador.format(bean.getId()));
			}
			beanform.setFlagTemporal("NO");
			
			
			session.saveOrUpdate(beanform);
			bean.setIdFormularioEmergencia(beanform.getId());
			session.saveOrUpdate(bean);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			throw e;
		}finally{
			session.close();
		}
	}

    public Long getNextPK(String sequence) throws Exception {
        long result = 1;

        StringBuffer sql = new StringBuffer("");
        sql.append("SELECT ");
        sql.append(sequence);
        sql.append(".NEXTVAL AS ID FROM DUAL");        
        
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = getSession().connection().prepareStatement(sql.toString());
            rs = pstmt.executeQuery();
            if(rs.next()) {
                result = rs.getLong(1);
            }
            pstmt.close();
            pstmt = null;
            rs.close();
            rs = null;
        }
        catch(Exception e) {
            log.error(e.getMessage());
            if(pstmt != null) {
                try {pstmt.close();} catch(Exception ignore) {}
            }
            if(rs != null) {
            	try {rs.close();}catch(Exception ignore) {}
            }
        }
        return new Long(result);
    }
	
} 